import json
from datetime import datetime

from flask import Blueprint, render_template, request, jsonify, session
from flask_jwt_extended import create_access_token, create_refresh_token, jwt_required, get_jwt_identity
from flask_login import login_required

from werkzeug.security import generate_password_hash

from applications.common import curd
from applications.common.curd import model_to_dicts, enable_status, disable_status, get_one_by_id, disable, enable, \
    update_userlevel
from applications.common.helper import ModelFilter
from applications.common.utils.getopenid import get_openid, token
from applications.common.utils.http import table_api, success_api, fail_api, wxuser_success_api
from applications.common.utils.rights import authorize
from applications.common.utils.validate import xss_escape
from applications.exts import db
from applications.exts.cache import cache
from applications.models import Role, Power, User, WxUser, UserLevel, Goods_Remark, Signtable

from applications.schemas import WxUserOutSchema
from applications.common.utils import upload as upload_curd

wxuser_user = Blueprint('wxuser', __name__, url_prefix='/wxuser/user')


# 用户管理
@wxuser_user.route('/')
@login_required
# flask 实现 Authorization请求报头认证

def main():
    return render_template('wxuser/user/main.html')


#   用户分页查询
@wxuser_user.route('/data')
@login_required
def data():
    # 获取请求参数
    openid = xss_escape(request.args.get('openid', type=str))
    username = xss_escape(request.args.get('username', type=str))
    # 查询参数构造
    mf = ModelFilter()
    if openid:
        mf.contains(field_name="openid", value=openid)
    if username:
        mf.contains(field_name="username", value=username)
    # if dept_id:
    #     mf.exact(field_name="dept_id", value=dept_id)
    # orm查询

    # 使用分页获取data需要.items
    wxuser = WxUser.query.filter(mf.get_filter(model=WxUser)).layui_paginate()
    count = wxuser.total
    # 返回api
    return table_api(data=model_to_dicts(schema=WxUserOutSchema, data=wxuser.items), count=count)


# 用户增加
@wxuser_user.route('/add')
@login_required
# @authorize("admin:user:add", log=True)
def add():
    return render_template('wxuser/user/add.html')


# 后台add用户
@wxuser_user.route('/adduser', methods=["POST"])
@login_required
# @authorize("admin:user:add", log=True)
def adduser():
    req_json = request.json

    print('req_json:', req_json)

    # code = xss_escape(req_json.get('code'))
    # userInfo = xss_escape(req_json.get('userInfo'))
    # print(code,userInfo)

    # code = req_json.get('code')
    # userInfo = req_json.get('userInfo')
    # username = userInfo.get('nickName')
    # avatarUrl = userInfo.get('avatarUrl')
    # openid = get_openid(code)
    # print(code, username, avatarUrl, openid)
    # wxtokens = token(code)
    # a = req_json.get("roleIds")
    username = xss_escape(req_json.get('username'))
    password = xss_escape(req_json.get('password'))
    phone = xss_escape(req_json.get('phone'))
    file = xss_escape(req_json.get('file'))

    wxuser = WxUser()
    wxuser.username = username
    wxuser.phone = phone
    wxuser.set_password(password)
    wxuser.avatar = file
    db.session.add(wxuser)
    db.session.commit()
    # # role_ids = a.split(',')
    #
    # if not username or not real_name or not password:
    #     return fail_api(msg="账号姓名密码不得为空")
    # #
    # if bool(User.query.filter_by(username=username).count()):
    #     return fail_api(msg="用户已经存在")
    # wxuser = WxUser(username=username, openid=openid, avatar=avatarUrl, enable=1)
    # user.set_password(password)
    # db.session.add(wxuser)
    # db.session.commit()
    # roles = Role.query.filter(Role.id.in_(role_ids)).all()
    # for r in roles:
    #     user.role.append(r)

    # wxuser_success_api(errno: int = 0, user:dict = {}, token:str = '', msg:str = ''):
    return success_api(msg="删除成功")


# 删除用户
@wxuser_user.route('/remove/<int:id>', methods=["DELETE"])
@login_required
# @authorize("admin:user:remove", log=True)
def delete(id):
    # user = User.query.filter_by(id=id).first()
    # user.role = []

    # res = User.query.filter_by(id=id).delete()

    res = WxUser.query.filter_by(id=id).delete()

    db.session.commit()
    print('res:', res)
    if not res:
        return fail_api(msg="删除失败")
    return success_api(msg="删除成功")


#  编辑用户
@wxuser_user.route('/edit/<int:id>')
@login_required
# @authorize("admin:user:edit", log=True)
def edit(id):
    wxuser = curd.get_one_by_id(WxUser, id)
    print(wxuser.username)
    # roles = Role.query.all()
    # checked_roles = []
    # for r in user.role:
    #     checked_roles.append(r.id)

    return render_template('wxuser/user/edit.html', wxuser=wxuser)


# 上传用户头像
@wxuser_user.route('/upload', methods=["POST"])
# @authorize("admin:file:add", log=True)
def upload_api():
    if 'file' in request.files:
        photo = request.files['file']
        mime = request.files['file'].content_type

        file_url = upload_curd.upload_one(photo=photo, mime=mime, type=1)
        file_url = request.host_url + file_url
        print(file_url)
        res = {
            "msg": "上传成功",
            "code": 0,
            "success": True,
            "data":
                {"src": file_url}
        }
        return jsonify(res)
    return fail_api()


#  编辑用户
@wxuser_user.route('/update', methods=["PUT"])
@login_required
# @authorize("admin:user:edit", log=True)
def update():
    req_json = request.json
    print(req_json)

    id = xss_escape(req_json.get("userId"))
    username = xss_escape(req_json.get('username'))
    phone = xss_escape(req_json.get('phone'))
    password = xss_escape(req_json.get('passwrd'))
    file = xss_escape(req_json.get("file"))

    # role_ids = a.split(',')
    wxu = WxUser.query.filter_by(id=id).first()
    if wxu:
        wxu.username = username
        wxu.avatar = file
        wxu.phone = phone
        wxu.password_hash = generate_password_hash(password)
        # User.query.filter_by(id=id).update({'username': username, 'realname': real_name, 'dept_id': dept_id})
        # wxu = WxUser.query.filter_by(id=id).first()
        #
        # roles = Role.query.filter(Role.id.in_(role_ids)).all()
        # u.role = roles
        #
        db.session.commit()
    return success_api(msg="更新成功")


# 启用用户
@wxuser_user.route('/enable', methods=["PUT"])
@login_required
# @authorize("admin:user:edit", log=True)
def enable_():
    _id = request.json.get('userId')
    if _id:
        res = enable(model=WxUser, id=_id)
        if not res:
            return fail_api(msg="出错啦")
        return success_api(msg="启动成功")
    return fail_api(msg="数据错误")


# 禁用用户
@wxuser_user.route('/disable', methods=["PUT"])
@login_required
# @authorize("admin:user:edit", log=True)
def dis_enable():
    _id = request.json.get('userId')
    if _id:
        res = disable(model=WxUser, id=_id)
        if not res:
            return fail_api(msg="出错啦")
        return success_api(msg="禁用成功")
    return fail_api(msg="数据错误")


# 批量删除
@wxuser_user.route('/batchRemove', methods=["DELETE"])
@login_required
# @authorize("admin:user:remove", log=True)
def batch_remove():
    ids = request.form.getlist('ids[]')
    for id in ids:
        # wxuser = WxUser.query.filter_by(id=id).first()
        # user.role = []

        res = WxUser.query.filter_by(id=id).delete()
        db.session.commit()
    return success_api(msg="批量删除成功")


# ===================wx========================

# 微信自动登录注册用户
@wxuser_user.route('/autosave', methods=["POST"])
# @authorize("admin:user:add", log=True)
def save():
    req_json = request.json
    # print('req_json:',req_json)

    # code = xss_escape(req_json.get('code'))
    # userInfo = xss_escape(req_json.get('userInfo'))
    # print(code,userInfo)

    code = req_json.get('code')
    userInfo = req_json.get('userInfo')
    username = userInfo.get('nickName')
    avatarUrl = userInfo.get('avatarUrl')
    openid = get_openid(code)
    print(code, username, avatarUrl, openid)
    wxtokens = token(code)
    print('wxtokens:', wxtokens)
    wxuser = WxUser()

    wxuser.username = username
    wxuser.openid = openid
    wxuser.avatar = avatarUrl
    wxuser.enable = 1
    wxuser.set_password('123456')

    # a = req_json.get("roleIds")
    # username = xss_escape(req_json.get('username'))
    # real_name = xss_escape(req_json.get('realName'))
    # password = xss_escape(req_json.get('password'))
    # # role_ids = a.split(',')
    #
    # if not username or not real_name or not password:
    #     return fail_api(msg="账号姓名密码不得为空")
    # #
    # wxuser=WxUser().filter_by(openid=openid).first()
    res = WxUser.query.filter_by(openid=openid).count()
    print('res:', res)
    access_token = create_access_token(identity=openid),
    print('access_token1：', type(access_token))
    refresh_token = create_refresh_token(identity=openid)
    if bool(res):
        # session['openid'] = openid
        # session['token'] = wxtokens
        # 缓存1天
        cache.set('openid', openid, timeout=8000)
        cache.set('token', wxtokens, timeout=8000)
        dbusers = WxUser.query.filter(WxUser.openid == openid).all()
        remark_count = Goods_Remark.query.filter(Goods_Remark.openid == openid).count()
        signtable = Signtable().query.filter(Signtable.openid == openid).first()
        if signtable:
            print(signtable.addtime)
            flagtable = signtable.status
        return wxuser_success_api(errno=0, access_token=str(access_token), refresh_token=refresh_token, user=userInfo,
                                  flagsing=flagtable, token=wxtokens, remark_count=remark_count, openid=openid,
                                  dbusers=model_to_dicts(schema=WxUserOutSchema, data=dbusers), msg='授权登录成功')
    else:
        db.session.add(wxuser)
        db.session.commit()
        # 添加积分表信息

        userlevel = UserLevel()
        userlevel.openid = openid
        db.session.add(userlevel)
        db.session.commit()
        # cache.set('openid', openid)
        # cache.set('token', wxtokens)
        # roles = Role.query.filter(Role.id.in_(role_ids)).all()
        # for r in roles:
        #     user.role.append(r)

        # wxuser_success_api(errno: int = 0, user:dict = {}, token:str = '', msg:str = ''):
        dbusers = WxUser.query.filter(WxUser.openid == openid).all()

        return wxuser_success_api(errno=0, access_token=str(access_token), refresh_token=refresh_token, user=userInfo,
                                  token=wxtokens, openid=openid,
                                  dbusers=model_to_dicts(schema=WxUserOutSchema, data=dbusers), msg='授权登录成功')
    # user.set_password(password)


# 用户登陆
@wxuser_user.route('/login', methods=["POST", "GET"])
def user_login():
    data = request.json  # 将前端Json数据转为字典
    print(data)
    username = data.get('username')
    password = data.get('password')
    if password == "123456":
        x = 1
    else:
        x = 0
    alluser = WxUser.query.all()
    for user in alluser:
        print('user.username:', user.username)
        if user.username == username and user.validate_password(password):
            userinfo = {
                'nickName': user.username,
                'avatarUrl': user.avatar
            }
            print('userinfo:', userinfo)
            openid = user.openid
            # 添加token

            access_token = create_access_token(identity=openid),
            refresh_token = create_refresh_token(identity=openid)
            msg = {
                'data': {'errno': 0, 'token': openid, 'refresh_token': refresh_token, 'access_token': str(access_token),
                         'userInfo': userinfo, 'msg': '登陆成功！！！'}}
            print(msg)
            msg['data']['x'] = x
        else:
            msg = {'data': {'errno': 1, 'token': 'openid', 'userInfo': 'userinfo', 'msg': '用户名或密码错误'}}
    print('msg:', msg)
    return msg


# 携带refresh_token请求此接口，刷新获的新的access_token
@wxuser_user.route("/refresh", methods=["POST", "GET"])
@jwt_required(refresh=True)  # 刷新token的装饰器，这是最新的写法
def refresh():
    identity = get_jwt_identity()
    access_token = create_access_token(identity=identity)  # str
    print(type(access_token))
    temp = []
    temp.append(access_token)
    print(temp)

    acc_token = tuple(temp)
    print('access_token:', acc_token)
    return wxuser_success_api(errno=0, access_token=str(acc_token), msg='token刷新成功')
    # return jsonify(errno=0,access_token=access_token)


@wxuser_user.route('/updatruser', methods=['POST', "GET"])
@jwt_required()
def updatruser():
    req_json = request.json
    openid = req_json.get('openid')
    user = WxUser.query.filter(WxUser.openid == openid).all()
    remark_count = Goods_Remark.query.filter(Goods_Remark.openid == openid).count()
    print(remark_count)
    users = model_to_dicts(schema=WxUserOutSchema, data=user)
    signtable = Signtable().query.filter(Signtable.openid == openid).all()
    # 获取当前的日期
    todattime = datetime.now().strftime("%Y-%m-%d")
    print('todattime:', todattime)
    if signtable:
        for item in signtable:
            # 获取数据库里面的时间
            times = item.addtime.strftime("%Y-%m-%d")
            print('times:',times)
            if times == todattime:
                # 签到了
                flagtable = item.status
            else:
                # 没签到
                flagtable = -1
    return wxuser_success_api(dbusers=users, flagsing=flagtable, remark_count=remark_count, msg='授权登录成功')


@wxuser_user.route('/userqiandao', methods=['POST', "GET"])
def userqiandao():
    req_sjon = request.json
    openid = req_sjon.get('openid')
    res = update_userlevel(openid=openid, num=1)
    signtable = Signtable().query.filter(Signtable.openid == openid).all()
    # 获取当前的日期
    todattime = datetime.now().strftime("%Y-%m-%d")
    if signtable:
        for item in signtable:
            times = item.addtime.strftime("%Y-%m-%d")
            if times == todattime:
                return wxuser_success_api(errno=1, msg='签到失败！')
            else:
                # 没签到
                if res:
                    sign = Signtable()
                    sign.openid = openid
                    try:
                        db.session.add(sign)
                        db.session.commit()
                    except Exception as e:
                        print(e)
                    return wxuser_success_api(msg='签到成功！', flagsing=0)
    return wxuser_success_api(errno=1, msg='签到失败！')
